package org.springblade.thingsphere.manage.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.pojo.entity.Dict;
import org.springblade.thingsphere.manage.excel.ComponentsExcel;
import org.springblade.thingsphere.manage.pojo.dto.ComponentConfig;
import org.springblade.thingsphere.manage.pojo.entity.ComponentsEntity;
import org.springblade.thingsphere.manage.pojo.vo.ComponentsVO;
import org.springblade.thingsphere.manage.service.IComponentsService;
import org.springblade.thingsphere.manage.wrapper.ComponentsWrapper;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 网络组件 控制器
 *
 * @author lhb
 * @since 2024-09-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-components/components")
@Tag(name = "网络组件", description = "网络组件接口")
public class ComponentsController extends BladeController {

	private final IComponentsService componentsService;

	@GetMapping("/dictionary")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "获取字典", description = "获取字典")
	public R<List<Dict>> dictionary(String code) {
		List<Dict> tree = new ArrayList<>();
		List<ComponentsEntity> list = componentsService.list(Wrappers.<ComponentsEntity>lambdaQuery()
			.eq(StrUtil.isBlank(code), ComponentsEntity::getStatus, 1)
		);
		for (ComponentsEntity components : list) {
			Dict dict = new Dict();
			dict.setId(components.getId());
			dict.setDictKey(StrUtil.toString(components.getId()));
			dict.setDictValue(components.getName());
			tree.add(dict);
		}
		return R.data(tree);
	}

	/**
	 * 网络组件 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入components")
	public R<ComponentsVO> detail(ComponentsEntity components) {
		ComponentsEntity detail = componentsService.getOne(Condition.getQueryWrapper(components));
		ComponentConfig componentConfig = JSONObject.parseObject(detail.getConfiguration(), ComponentConfig.class);
		ComponentsVO componentsVO = ComponentsWrapper.build().entityVO(detail);
		componentsVO.setClientId(componentConfig.getClientId());
		componentsVO.setThreadNum(componentConfig.getThreadNum());
		componentsVO.setHost(componentConfig.getHost());
		componentsVO.setPort(componentConfig.getPort());
		componentsVO.setReportPropertyPath(componentConfig.getReportPropertyPath());
		componentsVO.setUserName(componentConfig.getUserName());
		componentsVO.setPassword(componentConfig.getPassword());
		return R.data(componentsVO);
	}

	/**
	 * 网络组件 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入components")
	public R<IPage<ComponentsVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> components, Query query) {
		IPage<ComponentsEntity> pages = componentsService.page(Condition.getPage(query), Condition.getQueryWrapper(components, ComponentsEntity.class));
		IPage<ComponentsVO> componentsVOIPage = ComponentsWrapper.build().pageVO(pages);
		for (ComponentsVO record : componentsVOIPage.getRecords()) {
			ComponentConfig componentConfig = JSONObject.parseObject(record.getConfiguration(), ComponentConfig.class);
			record.setClientId(componentConfig.getClientId());
			record.setThreadNum(componentConfig.getThreadNum());
			record.setHost(componentConfig.getHost());
			record.setPort(componentConfig.getPort());
			record.setReportPropertyPath(componentConfig.getReportPropertyPath());
			record.setUserName(componentConfig.getUserName());
			record.setPassword(componentConfig.getPassword());
		}
		return R.data(componentsVOIPage);
	}

	/**
	 * 网络组件 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description = "传入components")
	public R submit(@Valid @RequestBody ComponentsVO components) {
		ComponentConfig componentConfig = new ComponentConfig();
		componentConfig.setThreadNum(components.getThreadNum());
		componentConfig.setHost(components.getHost());
		componentConfig.setPort(components.getPort());
		componentConfig.setClientId(components.getClientId());
		componentConfig.setUserName(components.getUserName());
		componentConfig.setPassword(components.getPassword());
		componentConfig.setReportPropertyPath(components.getReportPropertyPath());
		components.setConfiguration(JSONObject.toJSONString(componentConfig));
		components.setStatus(0);
		componentsService.dictClear();
		return R.status(componentsService.saveOrUpdate(components));
	}

	/**
	 * 网络组件 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.status(componentsService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 导出数据
	 */
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@GetMapping("/export-components")
	@ApiOperationSupport(order = 9)
	@Operation(summary = "导出数据", description = "传入components")
	public void exportComponents(@Parameter(hidden = true) @RequestParam Map<String, Object> components, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<ComponentsEntity> queryWrapper = Condition.getQueryWrapper(components, ComponentsEntity.class);
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(Components::getTenantId, bladeUser.getTenantId());
		//}
		queryWrapper.lambda().eq(ComponentsEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<ComponentsExcel> list = componentsService.exportComponents(queryWrapper);
		ExcelUtil.export(response, "网络组件数据" + DateUtil.time(), "网络组件数据表", list, ComponentsExcel.class);
	}

	/**
	 * 启用 (启动组件监听)
	 */
	@PostMapping("/start")
	public R<Boolean> start(@Valid @RequestBody ComponentsVO componentsVO) {
		return componentsService.start(componentsVO);
	}

	/**
	 * 停用 (卸载jar文件)
	 */
	@PostMapping("/stop")
	public R<Boolean> stop(@Valid @RequestBody ComponentsVO componentsVO) {
		return componentsService.stop(componentsVO);
	}
}
